import React, { useState, forwardRef, useImperativeHandle } from "react";
import { Form, Row, Col, Button, Space, Dropdown, MenuProps } from "antd";
import FormItem from "../FormItems/FormItem.tsx";
import { DownOutlined, UpOutlined } from "@ant-design/icons";
import { FormItemConfigs } from "../../global.ts";
// interface FormFieldConfig {
//   type: string;
//   name: string;
//   label?: string;
//   options?: any[];
//   showTime?: boolean;
//   range?: boolean;
//   render?: (form: any) => JSX.Element; // 假设 form 是当前 Form 实例的引用
// }

interface ISearchFormProps {
  formFieldConfig?: FormItemConfigs[];
  onSearch?: (
    searchConditions: any,
    currentPage: number,
    pageSize: number
  ) => void;
  onExport?: (searchConditions: any) => void;
  onBatchAdd?: () => void;
  onAdd?: () => void;
  onPrint?: () => void;
  showExportButton?: boolean; // 添加此属性以控制导出按钮的显示
  showBatchAddButton?: boolean; // 添加此属性以控制批量新增按钮的显示
  showAddButton?: boolean; // 添加此属性以控制新增按钮的显示
  showPrintButton?: boolean; // 添加此属性以控制打印按钮的显示
  layout?: 'single' | 'multiple'; // 添加布局属性
  expandThreshold?: number; // 添加展开阈值配置
}

export interface ISearchFormRef {
  submitForm: () => void;
  resetForm: () => void;
  getFormValues: () => any;
}
const SearchForm = forwardRef<ISearchFormRef, ISearchFormProps>(
  (
    {
      formFieldConfig,
      onSearch,
      onExport,
      onBatchAdd,
      onAdd,
      onPrint,
      showExportButton = false,
      showBatchAddButton = false,
      showAddButton = false,
      showPrintButton = false,
      layout = 'multiple', // 默认为多列布局
      expandThreshold = 3, // 默认值为3
    },
    ref
  ) => {
    const [form] = Form.useForm();
    const [expand, setExpand] = useState(false);

    useImperativeHandle(ref, () => ({
      submitForm: () => form.submit(),
      resetForm: () => form.resetFields(),
      getFormValues: () => form.getFieldsValue(),
    }));

    const handleExport = () => {
      const formValues = form.getFieldsValue();
      onExport?.(formValues);
    };

    const onFinish = (values: any) => {
      onSearch?.(values, 1, 10); // 假设当前页为1，每页10条数据
    };

    const additionalButtons = [
      showAddButton && { key: "add", label: "新增", onClick: onAdd },
      showExportButton && {
        key: "export",
        label: "导出",
        onClick: handleExport,
      },
      showBatchAddButton && {
        key: "batchAdd",
        label: "导入",
        onClick: onBatchAdd,
      },
      showPrintButton && { key: "print", label: "打印", onClick: onPrint },
    ].filter(Boolean) as { key: string; label: string; onClick: () => void }[];

    const menuItems: MenuProps["items"] = additionalButtons.map((button) => ({
      key: button.key,
      label: button.label,
      onClick: button.onClick,
    }));

    const renderAdditionalButtons = () => {
      if (additionalButtons.length === 0) {
        return null;
      }

      if (additionalButtons.length === 1) {
        const button = additionalButtons[0];
        return <Button onClick={button.onClick}>{button.label}</Button>;
      }

      return (
        <Dropdown.Button
          menu={{ items: menuItems.filter((item, index) => index !== 0) }}
          icon={<DownOutlined />}
          onClick={additionalButtons[0].onClick}
        >
          {additionalButtons[0].label}
        </Dropdown.Button>
      );
    };

    const renderFormItems = () => {
      const shouldShowExpand = (formFieldConfig?.length || 0) > expandThreshold;
      const visibleItems = shouldShowExpand && !expand 
        ? formFieldConfig?.slice(0, expandThreshold)
        : formFieldConfig;

      return visibleItems?.map((item, index) => (
        <Col 
          key={index} 
          {...(layout === 'single' 
            ? { span: 24 } 
            : { lg: 8, md: 12, sm: 24, xl: 8, xs: 24, xxl: 8 }
          )}
        >
          <FormItem item={item} index={index} style={{ marginBottom: 0 }} />
        </Col>
      ));
    };

    const renderExpandButton = () => {
      if ((formFieldConfig?.length || 0) <= expandThreshold) {
        return null;
      }

      return (
        <Button type="link" onClick={() => setExpand(!expand)}>
          {expand ? "收起" : "展开"}{" "}
          <UpOutlined 
            className="transition-transform duration-300" 
            rotate={expand ? 180 : 0} 
          />
        </Button>
      );
    };

    const getInitialValues = () => {
      const initialValues: any = {};
      formFieldConfig?.forEach((item) => {
        if (item.initialValue !== undefined) {
          initialValues[item.name] = item.initialValue;
        }
      });
      return initialValues;
    };

    return (
      <Form
        form={form}
        layout={layout === 'single' ? 'vertical' : 'horizontal'}
        onFinish={onFinish}
        initialValues={getInitialValues()}
      >
        <Row 
          gutter={[24, 12]}
          {...(layout === 'single' && { justify: 'start' })}
        >
          {renderFormItems()}
          <Col {...(layout === 'single' ? { span: 24 } : {})}>
            <Form.Item>
              <Space direction="horizontal">
                <Button type="primary" onClick={() => form.submit()}>
                  查询
                </Button>
                <Button onClick={() => form.resetFields()}>重置</Button>
                {renderAdditionalButtons()}
                {renderExpandButton()}
              </Space>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    );
  }
);

export default SearchForm;
